"""
Copyright © 2024 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-ws2812-digital-effect
"""
from random import randint
from time import sleep_ms
from ws2812 import WS2812
from config import Config


class DigitalEffect1(object):
	def __init__(self, leds:WS2812):
		self.__leds = leds
		self.__last_value = 0

	def show(self, value, x, y):
		'''在指定坐标显示数字'''
		if value not in Config.DIGITALS_1.keys():
			return

		out_frames = Config.DIGITALS_1[self.__last_value][Config.OUT]
		in_frames  = Config.DIGITALS_1[value][Config.IN]

		self.__show_effect(out_frames, x, y)
		self.__show_effect(in_frames, x, y)

		self.__last_value = value

	def __show_effect(self, frames, x, y):
		# 根据矩阵灯珠连接顺序，计算坐标对应的灯珠索引号
		start = x * Config.Matrix.HEIGHT + y

		for frame in frames:
			index = 0
			dots  = f'{frame:0>15b}'

			for dot in dots:
				led_index = start + index // Config.Font.HEIGHT * Config.Matrix.HEIGHT + index % Config.Font.HEIGHT
				self.__leds.set_pixel(led_index, Config.Colors.BRIGHT if dot == '1' else Config.Colors.BLACK)

				index += 1

			self.__leds.show()
			sleep_ms(50)

	@property
	def last_value(self):
		return self.__last_value

	@last_value.setter
	def last_value(self, value):
		self.__last_value = value


def main():
	leds = WS2812(Config.Matrix.WIDTH, Config.Matrix.HEIGHT, Config.Pin.DIN)

	leds.clean()
	leds.show()

	digital_1 = DigitalEffect1(leds)
	digital_2 = DigitalEffect1(leds)

	while True:
		value = randint(0, 9)
		digital_1.show(value, 1, 0)
		sleep_ms(200)

		value = randint(0, 9)
		digital_2.show(value, 5, 0)
		sleep_ms(200)


if __name__ == '__main__':
	main()
